<template>
  <div class="add_content">
    <el-input v-model="search" placeholder="请输入名称" clearable @input="filterTableList"></el-input>
    <div v-for="item in filterTableList" :key="item.id" class="food-item" @click="handleRowClick(item)" :style="{ 'background-image': 'url(' + item.image + ')' }">
      <div class="text">{{ item[searchKey] }}</div>
      <div class="mark"></div>
      <div v-if="selectedMap[item.id]" class="selected">{{ selectedMap[item.id].weight }}g</div>
    </div>
    <el-dialog title="填写重量" v-model="dialogVisible" width="400px">
      <el-form
        ref="listFormRef"
        :model="listForm"
        label-position="left"
        label-width="200px"
      >
        <el-form-item v-if="showNumber" label="数量" prop="number" :rules="[{ required: true, message: '请输入' }]">
          <el-input v-model="listForm.number" maxlength="9" />
        </el-form-item>
        <el-form-item label="重量(g)" prop="weight" :rules="[{ required: true, message: '请输入' }]">
          <el-input v-model="listForm.weight" maxlength="9" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog_footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, toRef, reactive, onMounted, defineProps, watch, computed } from 'vue'
import { Plus, Close, Odometer } from '@element-plus/icons-vue'
import { queryAllElementList, queryAllIngredientList, queryAllQuestionList, queryAllFood } from './api.js'

const props = defineProps({
  queryType: {
    type: String,
    default: 'element'
  },
  defaultData: {
    type: Array,
    default: () => []
  },
  showById: {
    type: String,
    default: ''
  },
  showNumber: {
    type: Boolean,
    default: false
  }
})

const dataList = ref([]) // 所有的数据
const selectedFood = ref([]) // 选中的数据
const selectedMap = ref({}) // 方便查找数据
const dialogVisible = ref(false)
let currentFood = null // 点击的食物，添加重量用
const search = ref('')
const listFormInit = {
  number: 1,
  weight: 0
}
const listForm = ref({ ...listFormInit })
const listFormRef = ref(null)
const searchKey = computed(() => {
  const map = {
    'question': 'content',
    'user': 'user_name',
    'element': 'name',
    'ingredient': 'name',
    'recipe': 'name'
  }
  return map[props.queryType] || 'name'
})
const filterTableList = computed(() => {
  if (!searchKey.value || !search.value) {
    return dataList.value
  }
  return dataList.value.filter(row => row[searchKey.value].includes(search.value))
})

watch(() => props.defaultData, (val) => {
  if (val) {
    selectedMap.value = {}
    selectedFood.value = JSON.parse(JSON.stringify(val))
    selectedFood.value.forEach(food => {
      selectedMap.value[food.id] = food
    })
  }
}, { deep: true, immediate: true })

onMounted(() => {
  switch (props.queryType) {
    case 'element':
      queryAllElementList().then(res => {
        getValue(res.result)
      })
      break
    case 'ingredient':
      queryAllIngredientList().then(res => {
        dataList.value = res.result
      })
      break
    case 'question':
      queryAllQuestionList().then(res => {
        getValue(res.result)
      })
      break
    case 'recipe':
      queryAllFood().then(res => {
        getValue(res.result)
      })
  }
})

const getValue = (data) => {
  dataList.value = data
}

const handleRowClick = (food) => {
  // 点击食物
  const { id, name } = food
  // 检查当前餐类型是否存在于 selectedFood 中，如果不存在则初始化为空数组
  if (!selectedFood.value) {
    selectedFood.value = []
  }

  // 将点击的id和name存储到变量中
  const existingFood = selectedFood.value.find((food) => food.id === id)
  if (!existingFood) {
    // 如果不存在，将食物添加到对应的餐类型
    currentFood = food

    // 初始化
    listForm.value = { ...listFormInit }
    dialogVisible.value = true
  } else {
    // 如果已经存在，取消选中
    selectedFood.value = selectedFood.value.filter((food) => food.id !== id)
    delete selectedMap.value[id]
  }
}

const submitAdd = () => {
  // 填写好重量后正式添加进去
  listFormRef.value.validate((valid) => {
    if (valid) {
      const { number, weight } = listForm.value
      const food = {
        ...currentFood,
        weight,
        number
      }
      selectedFood.value.push(food)
      selectedMap.value[food.id] = food

      dialogVisible.value = false
    }
  })
}

const getItem = ({ id, weight }) => {
  const obj = dataList.value.find(item => item.id === id)
  const name = obj[searchKey.value]
  return {
    name,
    weight,
    id
  }
}

const getSelectData = () => {
  return selectedFood.value
}

defineExpose({
  getSelectData
})

</script>

<style lang="scss" scoped>
.add_content {
  width: 100%;
  border-bottom: 1px solid #e2e2e2;
  border-radius: 5px;
  overflow-y: auto;
  text-align: left;
  // box-sizing: border-box;
  .add_operation {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 5px;
  }

  .add_item {
    width: 100%;
    line-height: 32px;
    padding: 0 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-bottom: 2px;
    text-align: left;
    box-sizing: border-box;

    .add_item_weight {
      display: inline-block;
      margin-left: 10px;

      ::v-deep .el-icon {
        transform: translateY(2px);
        color: gray;
      }

      .add_item_unit {
        color: rgb(206, 206, 206);
      }
    }

    .add_item_del {
      float: right;
      cursor: pointer;
      line-height: 36px;
      height: 32px;
    }
  }
}

::v-deep .el-form-item {
  display: block;
}
::v-deep .dialog_footer {
  display: flex;
}

.food-item {
  height: 60px;
  width: 60px;
  margin: 10px;
  margin-left: 0;
  border-radius: 20px;
  display: inline-block;
  // background-image: url("@/assets/猪肉.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  color: #fff;
  position: relative;
  overflow: hidden;

  .selected {
    position: absolute;
    top: 0;
    right: 0;
    width: 40px;
    height: 20px;
    border-bottom-left-radius: 10px;
    background-color: rgba(28, 128, 28, 0.8);
  }

  .text {
    font-size: 12px;
    font-weight: 500;
    position: absolute;
    text-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
    width: 100%;
    bottom: 10px;
    text-align: center;
    z-index: 99;
    color: #fff;
  }

  .mark {
    border-radius: 20px;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    // 线性渐变
    background: linear-gradient(180deg, rgba(0, 0, 0, 0) 30%, rgba(219, 32, 32, 0.4) 100%);
  }
}
</style>